// 当前选中的分组ID
let currentGroupId = null;
// 当前选中的股票代码
let currentStockCode = null;

$(document).ready(function () {
    // 初始化加载分组列表
    loadGroupList();

    // 搜索按钮点击事件
    $('#searchBtn').click(function () {
        const keyword = $('#searchKeyword').val().trim();
        if (keyword) {
            searchStocks(keyword);
        }
    });

    // 回车搜索
    $('#searchKeyword').keypress(function (e) {
        if (e.which === 13) {
            $('#searchBtn').click();
        }
    });

    // 添加分组按钮点击事件
    $('#addGroupBtn').click(function () {
        $('#groupName').val('');
        $('#groupDescription').val('');
        $('#addGroupModal').modal('show');
    });

    // 保存分组按钮点击事件
    $('#saveGroupBtn').click(function () {
        const name = $('#groupName').val().trim();
        const description = $('#groupDescription').val().trim();

        if (!name) {
            showToast('请输入分组名称', 'warning');
            return;
        }

        $.ajax({
            url: '/stockGroup/add',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                name: name,
                description: description
            }),
            success: function (res) {
                if (res.code === "0000") {
                    $('#addGroupModal').modal('hide');
                    loadGroupList();
                    showToast('分组创建成功', 'success');
                } else {
                    showToast('分组创建失败: ' + res.msg, 'error');
                }
            },
            error: function () {
                showToast('网络错误，请重试', 'error');
            }
        });
    });

    // 更新分组按钮点击事件
    $('#updateGroupBtn').click(function () {
        const id = $('#editGroupId').val();
        const name = $('#editGroupName').val().trim();
        const description = $('#editGroupDescription').val().trim();

        if (!name) {
            showToast('请输入分组名称', 'warning');
            return;
        }

        $.ajax({
            url: '/stockGroup/updateGroup/' + id,
            method: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify({
                name: name,
                description: description
            }),
            success: function (res) {
                if (res.code === "0000") {
                    $('#editGroupModal').modal('hide');
                    loadGroupList();
                    showToast('分组更新成功', 'success');
                } else {
                    showToast('分组更新失败: ' + res.msg, 'error');
                }
            },
            error: function () {
                showToast('网络错误，请重试', 'error');
            }
        });
    });
});

// 搜索股票
function searchStocks(keyword) {
    $.ajax({
        url: '/api/stocks/search',
        method: 'GET',
        data: {keyword: keyword},
        success: function (res) {
            if (res.code === "0000") {
                displaySearchResults(res.data);
            } else {
                showToast('搜索失败', 'error');
            }
        },
        error: function () {
            showToast('网络错误，请重试', 'error');
        }
    });
}

// 显示搜索结果
function displaySearchResults(stocks) {
    const container = $('#searchResults');
    container.empty();

    if (stocks.length === 0) {
        container.append('<div class="col-12"><p class="text-muted">未找到相关股票</p></div>');
        return;
    }

    stocks.forEach(stock => {
        // 检查是否需要显示星号
        const displayName = stock.monitorFlag === 1 ? `${stock.name} <span style="color: red;">★</span>` : stock.name;

        const card = $(`
            <div class="col-md-6 col-lg-4 mb-3">
                <div class="card stock-card h-100">
                    <div class="card-body">
                        <h5 class="card-title">${displayName}</h5>
                        <h6 class="card-subtitle mb-2 text-muted">${stock.code}</h6>
                        <button class="btn btn-sm btn-outline-primary add-to-group-btn"
                                data-stock-code="${stock.code}"
                                data-stock-name="${stock.name}">
                            添加到分组
                        </button>
                        <button class="btn btn-sm btn-outline-info view-detail-btn ms-2" 
                                data-stock-code="${stock.code}"
                                data-stock-name="${stock.name}">
                            详情
                        </button>
                    </div>
                </div>
            </div>
        `);

        container.append(card);
    });

    // 绑定添加到分组按钮事件
    $('.add-to-group-btn').click(function () {
        const stockCode = $(this).data('stock-code');
        const stockName = $(this).data('stock-name');
        showAddToGroupDialog(stockCode, stockName);
    });

    // 绑定查看详情按钮事件
    $('.view-detail-btn').click(function () {
        const stockCode = $(this).data('stock-code');
        const stockName = $(this).data('stock-name');
        showStockDetail(stockCode, stockName);
    });
}